﻿using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Media;
using Apps.Yunwei.YunWeiService;
using QDP.Platform.Silverlight;

namespace Apps.Yunwei.Views
{
    public partial class ExpressionEditor : UserControl
    {
        public ExpressionEditor()
        {
            InitializeComponent();
        }

        private string getValue(string parm, WidgetMetaAttribute attr)
        {
            Match match = Regex.Match(parm,attr.Key+"=(.+?);");
            if (match.Success)
            {
                return match.Groups[1].Value;
            }
            else
            {
                return attr.DefaultValue == null ?string.Empty:attr.DefaultValue.ToString().ToLower();
            }
        }
        private List<WidgetMetaAttribute> Source;
        private object Context;
        public void SetSource(List<WidgetMetaAttribute> source, object data)
        {
            Context = data;
            Source = source;
            string parms = (data as AppObject).Args;
            if (parms == null) parms = string.Empty;
            //LayoutRoot.Children.Clear();
            tabContainer.Items.Clear();
            var groups = source.OrderBy(p=>p.Key).GroupBy(p => p.Category);
            foreach (IGrouping<string,WidgetMetaAttribute> group in groups)
            {
                ScrollViewer scrollViewer = new ScrollViewer()
                {
                    Padding = new Thickness(5)
                };
                StackPanel stackPanel = new StackPanel();

                scrollViewer.Content = stackPanel;
                TabItem item = new TabItem()
                {
                    Header= group.Key,
                    Content = scrollViewer,
                };
                tabContainer.Items.Add(item);

                #region 处理子属性
                foreach (var meta in group.ToList())
                {
                    Control ctrl = null;
                    if (string.IsNullOrEmpty(meta.EnumValues))
                    {
                        if (meta.DefaultValue != null && (meta.DefaultValue.ToString().ToLower().Equals("true")
                            || meta.DefaultValue.ToString().ToLower().Equals("false")))
                        {

                            ctrl = new ToggleButton()
                            {
                                IsChecked = getValue(parms, meta).Equals("true")
                            };
                        }
                        else
                        {
                            ctrl = new TextBox() { Text = getValue(parms, meta), Width = 300 };
                        }
                    }
                    else
                    {
                        // 枚举值
                        ctrl = new ComboBox()
                        {
                            ItemsSource = meta.EnumValues.Split(','),
                            SelectedValue = getValue(parms, meta),
                            Width = 300
                        };
                    }
                    if (ctrl == null) continue; // 不存在控件时终止操作

                    if (stackPanel.FindName(meta.Key) != null) continue;// 控件重名时终止操作

                    Grid grid = new Grid();
                    
                    TextBlock textBlock = new TextBlock()
                    {
                        Text = meta.Key,
                        Height = 24,
                        FontWeight = FontWeights.Bold
                    };
                    grid.Children.Add(textBlock);

                    ctrl.Name = meta.Key;
                    ctrl.Tag = meta;
                    ctrl.Margin = new Thickness(150, 2, 0, 2);
                    ctrl.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;

                    grid.Children.Add(ctrl);

                    stackPanel.Children.Add(grid);

                    Border border = new Border()
                    {
                        BorderThickness = new Thickness(0, 0, 0, 1),
                        BorderBrush = new SolidColorBrush(Color.FromArgb(0x49, 0x00, 0x00, 0x00)),
                        Child = new TextBlock()
                        {
                            Foreground = new SolidColorBrush(Color.FromArgb(0xff, 0x99, 0x99, 0x99)),
                            TextWrapping = System.Windows.TextWrapping.Wrap,
                            Text = string.Format("描述：{0}\r\n默认：{1}"
                            , meta.Desc
                            , meta.DefaultValue == null
                                ? string.Empty
                                : meta.DefaultValue
                                    .ToString()
                                    .ToLower()
                                    .Replace("false", "否")
                                    .Replace("true", "是"))
                        }
                    };
                    stackPanel.Children.Add(border);
                }
                #endregion //#region 处理子属性
            }
        }

        public string GetResult()
        {
            string result = string.Empty;
            string format = "{0}={1};";

            foreach (TabItem tabItem in tabContainer.Items)
            {
                foreach (UIElement element in ((tabItem.Content as ScrollViewer).Content as StackPanel).Children)
                {
                    string text = string.Empty;
                    Control ctrl = null;
                    if ((element is Grid) == false) continue;

                    ctrl = ((element as Grid).Children[1]) as Control;

                    string key = ctrl.Name;
                    var meta = ctrl.Tag as WidgetMetaAttribute;
                    if (ctrl is TextBox)
                    {
                        text = (ctrl as TextBox).Text;
                        if (meta.DefaultValue != null && text.Equals(meta.DefaultValue.ToString().ToLower()))
                            text = string.Empty;
                    }
                    else if (ctrl is ToggleButton)
                    {
                        var cb = ctrl as ToggleButton;
                        text = cb.IsChecked.ToString().ToLower();
                        if (meta.DefaultValue != null && text.Equals(meta.DefaultValue.ToString().ToLower())) text = string.Empty;
                    }
                    else if (ctrl is CheckBox)
                    {
                        var cb = ctrl as CheckBox;
                        text = cb.IsChecked.ToString().ToLower();
                        if (meta.DefaultValue != null && text.Equals(meta.DefaultValue.ToString().ToLower())) text = string.Empty;
                        //text = (ctrl as CheckBox).IsChecked.ToString().ToLower();
                    }
                    else if (ctrl is ComboBox)
                    {
                        var c = (ctrl as ComboBox);
                        if (c.SelectedValue != null)
                            text = c.SelectedValue.ToString().ToLower();
                    }
                    if (string.IsNullOrEmpty(text) == false && text.Equals(meta.DefaultValue) == false)
                        result += string.Format(format, key, text);
                }
            }
            return result;
        }
    }
}
